package com.greyu.ysj.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.greyu.ysj.config.ResultStatus;
import com.greyu.ysj.entity.CbtVote;
import com.greyu.ysj.mapper.CbtVoteMapper;
import com.greyu.ysj.model.ResultModel;
import com.greyu.ysj.service.CbtVoteService;

@Service
@Transactional
public class CbtVoteServiceImpl implements CbtVoteService {
	@Autowired
	private CbtVoteMapper cbtVoteMapper;
	
	@Override
	public CbtVote selectVoteByuserId(Integer userId) {
		CbtVote cbtVote = this.cbtVoteMapper.selectByPrimaryKeyByUserID(userId);
		if (cbtVote == null){
			System.out.println("the cbtVote item for this userid is not exit~!");
			return null;
		}
		return cbtVote;
	}

	@Override
	//兑换票权，给用户增加票权
	public CbtVote updateAddVote(int userId, int vote) {
		CbtVote cbtVote = this.cbtVoteMapper.selectByPrimaryKeyByUserID(userId);
		if(cbtVote==null){
			cbtVote=new CbtVote();
			cbtVote.setUserId(userId);
			cbtVote.setVote(vote);
			this.cbtVoteMapper.insert(cbtVote);
		}
		//得到用户现有的票权数
		int votes=cbtVote.getVote();
		if(vote>0){
			cbtVote.setVote(votes+vote);
		}
		this.cbtVoteMapper.updateByPrimaryKey(cbtVote);
        return cbtVote;
	}
	//给币种投票，减少票权
	@Override
	public CbtVote updateReduceVote(int userId, int vote) {
		CbtVote cbtVote = this.cbtVoteMapper.selectByPrimaryKeyByUserID(userId);
		if(cbtVote==null){
			return null;
		 }
		//得到用户现有的票权数
		int votes=cbtVote.getVote();
		if(vote>0){
			cbtVote.setVote(votes-vote);
		}
		this.cbtVoteMapper.updateByPrimaryKey(cbtVote);
        return cbtVote;
	}

	@Override
	public ResultModel save(CbtVote cbtVote) {
		try {	
			if ( cbtVote.getUserId()==null
					||cbtVote.getVote()==null
	        		) {
	            return ResultModel.error(ResultStatus.DATA_NOT_NULL);
	        }
			//insert
	        this.cbtVoteMapper.insert(cbtVote);
		} catch (Exception e) {
			return ResultModel.error(ResultStatus.VOTE_INSERT_ERROR);
		}
	        return ResultModel.ok(cbtVote);
		}

}
